//
//  LoginNewViewController.m
//  JiaoWuGuanLi
//
//  Created by Zinzie on 14-2-17.
//  Copyright (c) 2014年 Zinzie. All rights reserved.
//

#import "LoginNewViewController.h"
#import "UIView+XHCustomHUD.h"
#import "TFHpple.h"
#import "MainInterfaceAppDelegate.h"
#import "DataModelController.h"
#import "tabBarViewController.h"
#import "CoreData+MagicalRecord.h"
#import "Student.h"

@interface LoginNewViewController (){
    BOOL firstAcc;
}
@property (strong, nonatomic) AFHTTPRequestOperationManager *AFHROM;
@property (copy,nonatomic) NSString *viewState;
@property (strong, nonatomic) IBOutlet UIButton *dengluButton;
@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *yanzhengIndi;
@property (weak, nonatomic) IBOutlet UIButton *btnRefresh;
@property (weak, nonatomic) IBOutlet UIView *yanZhengView;

@end

@implementation LoginNewViewController



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.yanzhengIndi.hidden = NO;
    [self.yanzhengIndi startAnimating];

    [self setNeedsStatusBarAppearanceUpdate];
    //[self shuaXinYanZhengMa];
    if ([[UIScreen mainScreen] bounds].size.height!=568) {
        self.dengluButton.hidden =YES;
    }
    self.yanZheng.hidden = YES;
    self.yanZhengView.alpha = 0;

    
    
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=YES;
    self.navigationController.navigationBarHidden=YES;
    self.yanZhengView.alpha = 0;
    self.yanZheng.hidden = YES;
    CGRect button = CGRectMake(64, 210, 192, 42);
    self.dengluButton.frame = button;


    
    

}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.checked = NO;
	// Do any additional setup after loading the view.
    //这编辑self.yanZhengImage
    //[self.zhangHao becomeFirstResponder];
    AFNetworkReachabilityManager *man=[AFNetworkReachabilityManager sharedManager];
    if (man.reachable) {
        NSLog(@"网络是否能连接");
    }else{
        NSLog(@"无网络连接");
    }
    }

- (IBAction)miMaBeginEditing {
    //check for local account
    int i = [Student MR_findByAttribute:@"xueHao" withValue:self.zhangHao.text].count;
    if (i == 0&&self.yanZheng.hidden==YES) {
        CGRect button = CGRectMake(64, 259, 192, 42);
        [UIView animateWithDuration:0.2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             self.yanZhengView.alpha = 1;
                             self.dengluButton.frame = button;
                         }
                         completion:^(BOOL finished) {
                             self.yanZheng.hidden = NO;
                         }];

        [self shuaXinYanZhengMa];
    }else if (i != 0 && self.yanZheng.hidden==NO){
        CGRect button = CGRectMake(64, 210, 192, 42);
        [UIView animateWithDuration:0.2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             self.yanZhengView.alpha = 0;
                             self.dengluButton.frame = button;
                         }
                         completion:^(BOOL finished) {
                             self.yanZheng.hidden = YES;
                         }];
    
    }
    
}

- (IBAction)nextPressed {

    [self.Mima becomeFirstResponder];
}

- (IBAction)goPressed {
    [self.Mima resignFirstResponder];
    if (self.yanZheng.hidden==NO) {
        [self.yanZheng becomeFirstResponder];
    }else{
        [self logIn];    //本地login
    }
}
- (IBAction)logIn {
    [self touchOutside];
    
    if (self.checked == YES) {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        if (self.yanZheng.hidden==YES) {//本地登录
            Student *user = [[Student MR_findByAttribute:@"xueHao" withValue:self.zhangHao.text] lastObject];
            NSLog(@"local login %@,%@",user.miMa,self.Mima.text);
            if ([user.miMa isEqualToString: self.Mima.text]) {
                NSLog(@"local login yes");
                self.xueHao = user.xueHao;
                self.xingMing = user.mingCheng;
                [userDefault setBool:NO forKey:@"online"];
                [self chengGong];
            }else{
                [self.view showHUDWithText:@"学号或密码错误" hudType:kXHHUDError animationType:kXHHUDFade delay:1];
                self.Mima.text = @"";
                
                }
            
            
            
        }else{
            [userDefault setBool:YES forKey:@"online"];
        dispatch_queue_t only=dispatch_queue_create("only", NULL);
        if (!self.viewState) {
            NSLog(@"没有viewstate");
            dispatch_async(only, ^{
                [self acquireViewStare];
            });
        }else{
            NSLog(@"有state%@直接登录",self.viewState);
            dispatch_async(only, ^{
                [self logins];
            });
        }
        }
        
        
    }
    
    
    else{
        [self inputCheck];
    }
    self.checked = NO;
    
    
    
    
    }


-(void)acquireViewStare{
    [self.AFHROM GET:@"http://gdjwgl.bjut.edu.cn/default2.aspx" parameters:nil
             success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
                 
                 NSData *data=responseObject;
                 NSString *transStr=[[NSString alloc]initWithData:data encoding:enc];
                 
                 NSString *utf8HtmlStr = [transStr stringByReplacingOccurrencesOfString:@"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">" withString:@"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"];
                 NSData *htmlDataUTF8 = [utf8HtmlStr dataUsingEncoding:NSUTF8StringEncoding];
                 TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:htmlDataUTF8];
                 NSArray *elements  = [xpathParser searchWithXPathQuery:@"//input[@name='__VIEWSTATE']"];
                 
                 // Access the first cell
                 NSUInteger count=[elements count];
                 for (int i=0; i<count; i++) {
                     TFHppleElement *element = [elements objectAtIndex:i];
                     self.viewState=[element objectForKey:@"value"];
                     //                  [self huoDevs];
                     NSLog(@"1提取到得viewstate为%@",self.viewState);
                     [self logins];
                     
                     
                 }
             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 NSLog(@"Error: %@", [error debugDescription]);
             }];//获取登陆后的网页
    //    NSLog(@"1提取到得viewstate为%@",viewstates);
    //    self.viewState=viewstates;
    NSLog(@"2提取到得viewstate为%@",self.viewState);
    
}
-(void)logins{
    [self.view showHUDWithText:@"登录中" hudType:kXHHUDLoading animationType:kXHHUDFade delay:0];
    NSString *xueHaoSe=self.zhangHao.text;
    self.xueHao=xueHaoSe;
    NSDictionary *parameters = @{@"__VIEWSTATE":self.viewState,@"txtUserName": xueHaoSe,@"TextBox2":self.Mima.text,@"txtSecretCode":self.yanZheng.text,@"RadioButtonList1":@"学生",@"Button1":@""};
    [self.AFHROM POST:@"http://gdjwgl.bjut.edu.cn/default2.aspx" parameters:parameters
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  NSURL *denglu=[NSURL URLWithString:@"http://gdjwgl.bjut.edu.cn/default2.aspx"];
                  if ([operation.response.URL isEqual:denglu]) {
                      [self miMaCuoWu];
                      NSLog(@"登陆错误");
                  }else{
                      NSLog(@"登陆成功");
                      
                      NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);

                      NSData *data=responseObject;
                      NSString *tansData=[[NSString alloc]initWithData:data encoding:enc];
                      
//                      NSLog(@"转化过的string为%@",tansData);
                      
                  NSLog(@"biaodantijiaochenggong:%ld，%@",(long)operation.response.statusCode,operation.responseString);//提交表单
                  NSString *utf8HtmlStr = [tansData stringByReplacingOccurrencesOfString:@"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">" withString:@"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"];
                  NSData *htmlDataUTF8 = [utf8HtmlStr dataUsingEncoding:NSUTF8StringEncoding];
                      [self anayseLoginData:htmlDataUTF8];
                  }
              } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  NSLog(@"Error: %@", @"???");
              }];
}
-(void)anayseLoginData:(NSData*)data{
    TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:data];
    NSArray *elements  = [xpathParser searchWithXPathQuery:@"//span[@id='xhxm']"];
    
    // Access the first cell
    NSUInteger count=[elements count];
    for (int i=0; i<count; i++) {
        TFHppleElement *element = [elements objectAtIndex:i];
        
        // Get the text within the cell tag
        NSString *content = [element text];
        NSString *ta=[element tagName];
        //              NSLog(@"之前%@",self.viewState);
        //              self.viewState=[element objectForKey:@"value"];
        //              NSLog(@"之后%@",self.viewState);
//        NSString *namess=[content substringFromIndex:10];
        self.xingMing=[content substringToIndex:[content length]-2];
        NSLog(@"学号姓名为%@%@%@",content,ta,_xingMing);
    }
    //Get all the cells of the 2nd row of the 3rd table
    [self chengGong];

}
- (IBAction)touchOutside {
    //点击其他地方退出键盘
    [self.zhangHao resignFirstResponder];
    [self.Mima resignFirstResponder];
    [self.yanZheng resignFirstResponder];
}
- (IBAction)didFinish {
    [self.yanZheng resignFirstResponder];
    [self logIn];
}
- (IBAction)chengGong {
//    [NSUserDefaults resetStandardUserDefaults];
//    NSUserDefaults *defaultss=[NSUserDefaults standardUserDefaults];
//    NSDictionary *coodDic=self.AFHROM.cookieDictionary;
//    [defaultss setObject:coodDic forKey:@"cookie"];
//    [defaultss synchronize];
    [self.view dismissHUD:self.view.hudView delay:0];
    [self performSelector:@selector(chengGongs) withObject:nil afterDelay:0.2];
    }

-(void)chengGongs{
    [self.view showHUDWithText:@"登录成功" hudType:kXHHUDSuccess animationType:kXHHUDFade delay:1.5];
    NSPredicate *student = [NSPredicate predicateWithFormat:@"xueHao CONTAINS[cd] %@",self.zhangHao.text];
    if ([Student MR_findAllWithPredicate:student].count==0) {
        
    Student *new = [Student MR_createEntity];
    new.xueHao = self.zhangHao.text;
    new.miMa = self.Mima.text;
    new.mingCheng = self.xingMing;
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"储存成功啦啦啦啦啦啦啦");
        }else{
            NSLog(@"没有存上");
        }
    }];
    }else{
        NSLog(@"数据库里已经有啦啦啦啦啦啦啦");
    }
    [self performSelector:@selector(tuiChuJieMian) withObject:Nil afterDelay:1.5];

}
-(void)tuiChuJieMian{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.zhangHao.text forKey:@"zhangHao"];
    [userDefaults setObject:self.Mima.text forKey:@"miMa"];
    [userDefaults setObject:self.xingMing forKey:@"xingMing"];
    [userDefaults synchronize];
    NSUserDefaults *defaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.ZhangZhang.TodayExtensionSharingDefaults"];
    [defaults setBool:YES forKey:@"logged"];
//    tabBarViewController *tabbar=[[tabBarViewController alloc]init];
    [self performSegueWithIdentifier:@"DengLuSegue" sender:self];
    self.navigationController.navigationBarHidden=YES;
    [self clearInput];
}
- (IBAction)miMaCuoWu {
    [self.view dismissHUD:self.view.hudView delay:0];
    [self performSelector:@selector(miMaCuoWuStep2) withObject:nil afterDelay:0.2];
//    [self.view showHUDWithText:@"学号或密码错误" hudType:kXHHUDError animationType:kXHHUDFade delay:2.0];
//    [self shuaXinYanZhengMa];

}

-(void)miMaCuoWuStep2{
    [self.view showHUDWithText:@"学号或密码错误" hudType:kXHHUDError animationType:kXHHUDFade delay:1];
    self.AFHROM.cookieDictionary=nil;
    self.viewState=nil;
    [self shuaXinYanZhengMa];
    [self clearInput];

}

-(void)clearInput{
    self.Mima.text = @"";
    self.yanZheng.text = @"";
}

-(void)inputCheck{
    if ([self.zhangHao.text isEqualToString:@""]) {
        [self.zhangHao becomeFirstResponder];
    }
        else if ([self.Mima.text isEqualToString:@""]){
        [self.Mima becomeFirstResponder];
            }
            else if (self.yanZheng.hidden==NO&&[self.yanZheng.text isEqualToString:@""]){
                [self.yanZheng becomeFirstResponder];
                }
            else {
                self.checked = YES;
                [self logIn];
            }
}
- (IBAction)huanYanzheng {
        [self shuaXinYanZhengMa];
}
-(void)shuaXinYanZhengMa{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSMutableURLRequest *UrlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: @"http://gdjwgl.bjut.edu.cn/CheckCode.aspx"]];
    //提交Cookie，上一行的NSURLRequest被改为NSMutableURLRequest
    
    if(self.AFHROM.cookieDictionary) {
        [UrlRequest setHTTPShouldHandleCookies:NO];
        
        [UrlRequest setAllHTTPHeaderFields:self.AFHROM.cookieDictionary];
    }
    
    //end
    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:UrlRequest];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Response: %@", responseObject);
        dispatch_async(dispatch_get_main_queue(), ^{
            self.yanZhengImage.image = responseObject;
            self.yanzhengIndi.hidden= YES;
        });
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"无法连接网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    
    }];
    [requestOperation start];

    // 显示验证码
    });

    
}
-(void)setXueHao:(NSString *)xueHao{
    _xueHao = xueHao;
    MainInterfaceAppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.XueHao = _xueHao;
    NSLog(@"%@",myDelegate.XueHao);
}
-(void)setXingMing:(NSString *)xingMing{
    _xingMing=xingMing;
    MainInterfaceAppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.userName = _xingMing;

}


-(AFHTTPRequestOperationManager*)AFHROM{
    if (!_AFHROM) {
        
        _AFHROM=[AFHTTPRequestOperationManager manager];
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
        _AFHROM.responseSerializer.stringEncoding=enc;
        _AFHROM.requestSerializer.stringEncoding = enc;
        _AFHROM.responseSerializer=[AFHTTPResponseSerializer serializer];
        _AFHROM.requestSerializer = [AFHTTPRequestSerializer serializer];
        //        return _AFHROM;
    }
    return _AFHROM;
}
@end
